// 初始化操作
$.ajax({
    url:"shop/userList",
    type:"get",
    success:function (res){
        $("#editShopOwnerId").append(`<option value="">所有用户</option>`)
        $("#addShopOwnerId").append(`<option value=>所有用户</option>`)
        for(var i = 0;i<res.data.length;i++){
            $("#addShopOwnerId").append(`<option value="${res.data[i].id}">${res.data[i].username}</option>`)
            $("#editShopOwnerId").append(`<option value="${res.data[i].id}">${res.data[i].username}</option>`)
        }
    },
    error:function (err){
        console.log(err)
    }
})
const avatardata = new FormData();

$.ajax({
    url:"shop/tag",
    type:"get",
    success:function (res){
        var arr = res.data;
        $("#categoryFilter").html("")
        $("#categoryFilter").append('<option value="">所有品类</option>')
        for(var i = 0 ;i<arr.length;i++){
            $("#categoryFilter").append(`<option value="${res.data[i].id}">${res.data[i].tagName}</option>`)
        }
        console.log(res.data)
    }

})
/**
 * 店铺管理系统 - 基于shops数据库
 */

// 全局变量
let shops = [];
let currentPage = 1;
let rowsPerPage = 10;
let totalPages = 0;
let totalShops = 0;

// DOM元素
const tableBody = document.getElementById('tableBody');
const pageNumbers = document.getElementById('pageNumbers');
const prevPage = document.getElementById('prevPage');
const nextPage = document.getElementById('nextPage');
const shopModal = document.getElementById('shopModal');
const closeModal = document.getElementById('closeModal');
const shopForm = document.getElementById('shopForm');
const modalTitle = document.getElementById('modalTitle');
const pageSizeSelect = document.getElementById('pageSize');
const shopName = document.getElementById('shopName');
const ownerId = document.getElementById('ownerId');
const searchBtn = document.getElementById('searchBtn');
const loader = document.getElementById('compact-loader');
const category = document.getElementById('categoryFilter');

// 初始化页面
function init() {
    renderTable();
    renderPagination();
    addEventListeners();
}

// 渲染表格
function renderTable() {
    showLoader();
    const searchData = {
        tag:category.value || '',
        name: shopName.value || '',
        username: ownerId.value || '',
        page: currentPage,
        pageSize: rowsPerPage
    };
    console.log(searchData)

    $.ajax({
        url: '/shop/list',
        type: 'POST',
        async: false,
        data: searchData,
        success: function (data) {
            console.log(data)
            if (data.code==200) {
                shops = data.data.rows || [];
                totalShops = data.data.total || 0;
                totalPages = Math.ceil(totalShops / rowsPerPage);
                tableBody.innerHTML = '';
                if (shops.length === 0) {
                    tableBody.innerHTML = `
                        <tr>
                            <td colspan="8" class="text-center py-4 text-muted">
                                <i class="bi bi-inbox"></i> 暂无店铺数据
                            </td>
                        </tr>
                    `;
                    return;
                }

                shops.forEach(shop => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${shop.id}</td>
                        <td>${escapeHtml(shop.name || '')}</td>
                        <td>
                            ${shop.avatarUrl ?
                        `<img src="${shop.avatarUrl}" class="shop-img" alt="${shop.name}的头像" onerror="this.style.display='none';this.nextElementSibling.style.display='flex';">
                                 <div class="shop-img-placeholder" style="display:none;"><i class="bi bi-shop"></i></div>` :
                        `<div class="shop-img-placeholder"><i class="bi bi-shop"></i></div>`
                    }
                        </td>
                        <td>${escapeHtml(shop.desc || '暂无简介')}</td>
                        <td><span class="rating">${shop.rating || 0}</span></td>
                        <td>${shop.ratingCount || 0}</td>
                        <td>${shop.username || ''}</td>
                        <td>
                            <button class="btn-view" data-id="${shop.id}">
                                <i class="bi bi-eye"></i> 查看
                            </button>
                            <button class="btn-edit" data-id="${shop.id}">
                                <i class="bi bi-pencil"></i> 编辑
                            </button>
                            <button class="btn-delete" data-id="${shop.id}">
                                <i class="bi bi-trash"></i> 删除
                            </button>
                        </td>
                    `;
                    tableBody.appendChild(row);
                });
            } else {
                showError('加载店铺数据失败: ' + data.message);
            }
        },
        error: function(xhr, status, error) {
            showError('网络请求失败: ' + error);
        },
        complete: function() {
            hideLoader();
        }
    });
}

// 渲染分页
function renderPagination() {
    pageNumbers.innerHTML = '';

    // 上一页按钮状态
    prevPage.disabled = currentPage === 1;

    // 下一页按钮状态
    nextPage.disabled = currentPage === totalPages || totalPages === 0;

    // 如果没有数据或只有一页，显示单个页码
    if (totalPages <= 1) {
        if (totalPages === 1) {
            const pageBtn = document.createElement('button');
            pageBtn.className = 'page-btn active';
            pageBtn.textContent = '1';
            pageBtn.addEventListener('click', () => goToPage(1));
            pageNumbers.appendChild(pageBtn);
        }
        return;
    }

    // 多页情况下的页码显示逻辑
    const maxVisiblePages = 5;
    let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
    let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);

    // 调整起始页，确保显示足够的页码
    if (endPage - startPage + 1 < maxVisiblePages) {
        startPage = Math.max(1, endPage - maxVisiblePages + 1);
    }

    // 显示第一页和省略号（如果需要）
    if (startPage > 1) {
        const firstPage = document.createElement('button');
        firstPage.className = 'page-btn';
        firstPage.textContent = '1';
        firstPage.addEventListener('click', () => goToPage(1));
        pageNumbers.appendChild(firstPage);

        if (startPage > 2) {
            const ellipsis = document.createElement('span');
            ellipsis.textContent = '...';
            ellipsis.style.padding = '0 10px';
            ellipsis.style.color = '#6c757d';
            pageNumbers.appendChild(ellipsis);
        }
    }

    // 显示中间页码
    for (let i = startPage; i <= endPage; i++) {
        const pageBtn = document.createElement('button');
        pageBtn.className = `page-btn ${i === currentPage ? 'active' : ''}`;
        pageBtn.textContent = i;
        pageBtn.addEventListener('click', () => goToPage(i));
        pageNumbers.appendChild(pageBtn);
    }

    // 显示最后一页和省略号（如果需要）
    if (endPage < totalPages) {
        if (endPage < totalPages - 1) {
            const ellipsis = document.createElement('span');
            ellipsis.textContent = '...';
            ellipsis.style.padding = '0 10px';
            ellipsis.style.color = '#6c757d';
            pageNumbers.appendChild(ellipsis);
        }

        const lastPage = document.createElement('button');
        lastPage.className = 'page-btn';
        lastPage.textContent = totalPages;
        lastPage.addEventListener('click', () => goToPage(totalPages));
        pageNumbers.appendChild(lastPage);
    }
}
// 跳转到指定页码
function goToPage(page) {
    if (page < 1 || page > totalPages) return;
    currentPage = page;
    renderTable();
    renderPagination();
}

// 显示加载动画
function showLoader() {
    loader.style.display = 'flex';
}

// 隐藏加载动画
function hideLoader() {
    loader.style.display = 'none';
}

// 显示成功消息
function showSuccess(message) {
    const alert = document.getElementById('success-alert');
    const messageSpan = document.getElementById('success-message');
    messageSpan.textContent = message;
    alert.style.display = 'flex';

    setTimeout(() => {
        alert.style.display = 'none';
    }, 2000);
}

// 显示错误消息
function showError(message) {
    const alert = document.getElementById('error-alert');
    const messageSpan = document.getElementById('error-message');
    messageSpan.textContent = message;
    alert.style.display = 'flex';

    setTimeout(() => {
        alert.style.display = 'none';
    }, 2000);
}

// HTML转义函数
function escapeHtml(unsafe) {
    return unsafe
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#039;");
}

// 添加事件监听器
function addEventListeners() {
    // 分页按钮
    prevPage.addEventListener('click', () => goToPage(currentPage - 1));
    nextPage.addEventListener('click', () => goToPage(currentPage + 1));

    // 每页显示条数选择器
    pageSizeSelect.addEventListener('change', (e) => {
        rowsPerPage = parseInt(e.target.value);
        currentPage = 1;
        renderTable();
        renderPagination();
    });

    // 搜索按钮
    searchBtn.addEventListener('click', () => {
        currentPage = 1;
        renderTable();
        renderPagination();
    });





    // 点击模态框外部关闭
    window.addEventListener('click', (e) => {
        if (e.target === shopModal) {
            shopModal.style.display = 'none';
        }
    });


    // 表格按钮事件委托
    tableBody.addEventListener('click', (e) => {
        const target = e.target.closest('button');
        if (!target) return;

        const id = parseInt(target.getAttribute('data-id'));
        const shop = shops.find(s => s.id === id);
        if (!shop) return;

        if (target.classList.contains('btn-edit')) {
            // 编辑按钮
            editShop(shop.id)
        } else if (target.classList.contains('btn-delete')) {
            // 删除按钮
            if (confirm(`确定要删除店铺 "${shop.name}" 吗？`)) {
                $.ajax({
                    url: "/shop/deleteById",
                    type: "POST",
                    async: false,
                    data: { id: id },
                    success: function (response) {
                        if (response.code==200) {
                            showSuccess('店铺删除成功');
                            renderTable();
                            renderPagination();
                        } else {
                            showError('删除失败: ' + response.message);
                        }
                    },
                    error: function(xhr, status, error) {
                        showError('删除失败: ' + error);
                    }
                });
            }
        } else if (target.classList.contains('btn-view')) {
            // 查看按钮 - 可以跳转到详情页面或显示详情模态框
            // alert(`查看店铺: ${shop.name}\n简介: ${shop.desc}\n评分: ${shop.rating}`);
            viewShop(shop.id);
        }
    });

    // 提示框关闭按钮
    document.querySelectorAll('.alert-close').forEach(btn => {
        btn.addEventListener('click', (e) => {
            e.target.closest('.alert').style.display = 'none';
        });
    });
}

// 初始化应用
document.addEventListener('DOMContentLoaded', init);
var imgs=[]
// 打开添加店铺模态框
function openAddShopModal() {
    imgs=[]
    // 重置表单
    document.getElementById('addShopForm').reset();

    // 重置头像预览
    const avatarPreview = document.getElementById('addShopAvatarPreview');
    const avatarPlaceholder = document.getElementById('addShopAvatarPlaceholder');
    avatarPreview.style.display = 'none';
    avatarPlaceholder.style.display = 'flex';
    avatarPreview.src = '';

    // 重置店铺图片预览
    const imagesPreview = document.getElementById('addShopImagesPreview');
    const existingImages = imagesPreview.querySelectorAll('.image-preview-item:not(.add-image-btn)');
    existingImages.forEach(img => img.remove());
    updateAddShopImageButtonVisibility();

    // 显示模态框
    document.getElementById('addShopModal').style.display = 'flex';

    // 初始化上传功能
    initAddShopUploads();
}

// 初始化添加店铺上传功能
function initAddShopUploads() {
    initAddShopAvatarUpload();
    initAddShopImagesUpload();
}

// 初始化头像上传
function initAddShopAvatarUpload() {
    const avatarInput = document.getElementById('addShopAvatar');
    const preview = document.getElementById('addShopAvatarPreview');
    const placeholder = document.getElementById('addShopAvatarPlaceholder');
    const previewWrapper = document.querySelector('#addShopModal .avatar-preview-wrapper');

    // 点击预览区域选择文件
    previewWrapper.addEventListener('click', () => {
        avatarInput.click();
    });

    // 文件选择变化
    avatarInput.addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (file) {
            if (!validateImageFile(file)) {
                this.value = '';
                return;
            }

            const reader = new FileReader();
            reader.onload = function(event) {
                preview.src = event.target.result;
                preview.style.display = 'block';
                placeholder.style.display = 'none';
                const formData = new FormData();
                console.log("file是什么"+file)
                formData.append("file", file);  // "file" 必须和后端参数名一致
                $.ajax({
                    url: "/upload",  // 替换为你的Servlet URL
                    type: "POST",
                    data: formData,
                    processData: false,      // 禁止jQuery处理数据（文件上传必须）
                    contentType: false,      // 禁止设置Content-Type（浏览器自动生成multipart/form-data）
                    cache: false,            // 禁用缓存// 禁止设置Content-Type请求头（浏览器会自动设置）
                    success: function (response) {
                        imgSrc = response.data
                        console.log(imgSrc)
                        document.getElementById('addShopAvatarPreview').src=imgSrc
                    },error: function(xhr, status, error) {
                        console.error("上传失败:", error);
                        $("#result").html("上传失败: " + (xhr.responseText || error));
                    }
                });
            };
            reader.readAsDataURL(file);
        }
    });
}

// 初始化店铺图片上传
function initAddShopImagesUpload() {
    const imagesInput = document.getElementById('addShopImages');

    imagesInput.addEventListener('change', function(e) {
        const files = Array.from(e.target.files);
        if (files.length > 0) {
            handleAddShopImagesUpload(files);
        }
    });
}

// 触发添加店铺图片上传
function triggerAddShopImagesUpload() {
    document.getElementById('addShopImages').click();
    console.log(1)
    avatardata.append("files",document.getElementById('addShopImages').files[0])
    console.log(avatardata)
    // 验证是否添加成功
    console.log("FormData条目数量:", Array.from(avatardata.entries()).length);
}

// 处理添加店铺图片上传
function handleAddShopImagesUpload(files) {
    const previewContainer = document.getElementById('addShopImagesPreview');
    const existingImages = previewContainer.querySelectorAll('.image-preview-item:not(.add-image-btn)');
    // console.log(111)
    const imagesInput = document.getElementById('addShopImages');
    const formdata = new FormData()
    formdata.append("file",imagesInput.files[0])
    console.log(imagesInput.files[0])
    // formData.append("file", file);  // "file" 必须和后端参数名一致
    let img = null;
    $.ajax({
        url: "/upload",  // 替换为你的Servlet URL
        type: "POST",
        data: formdata,
        processData: false,      // 禁止jQuery处理数据（文件上传必须）
        contentType: false,      // 禁止设置Content-Type（浏览器自动生成multipart/form-data）
        cache: false, // 禁用缓存// 禁止设置Content-Type请求头（浏览器会自动设置）
        async:false,
        success: function (response) {
            img = response.data
            console.log(img)
        },error: function(xhr, status, error) {
            console.error("上传失败:", error);
            $("#result").html("上传失败: " + (xhr.responseText || error));
        }
    });
    // 检查图片数量限制
    if (existingImages.length + files.length > 6) {
        showErrorAlert('最多只能上传6张图片');
        return;
    }

    files.forEach((file, index) => {
        if (!validateImageFile(file)) return;

        const reader = new FileReader();
        reader.onload = function(event) {
            const imageItem = createAddImagePreviewItem(img, img);
            // 插入到添加按钮之前
            const addBtn = previewContainer.querySelector('.add-image-btn');
            previewContainer.insertBefore(imageItem, addBtn);
        };
        reader.readAsDataURL(file);
    });

    // 更新添加按钮可见性
    updateAddShopImageButtonVisibility();
}

// 创建添加图片预览项
function createAddImagePreviewItem(src, filename) {
    const item = document.createElement('div');
    item.className = 'image-preview-item';
    item.innerHTML = `
        <img src="${src}" alt="${filename}">
        <button type="button" class="image-remove-btn" onclick="removeAddShopImage(this)">
            <i class="bi bi-x"></i>
        </button>
    `;
    return item;
}

// 移除添加店铺图片
function removeAddShopImage(button) {
    const item = button.closest('.image-preview-item');
    item.remove();
    updateAddShopImageButtonVisibility();
}

// 更新添加按钮可见性
function updateAddShopImageButtonVisibility() {
    const previewContainer = document.getElementById('addShopImagesPreview');
    const existingImages = previewContainer.querySelectorAll('.image-preview-item:not(.add-image-btn)');
    const addBtn = previewContainer.querySelector('.add-image-btn');

    if (existingImages.length >= 6) {
        addBtn.style.display = 'none';
    } else {
        addBtn.style.display = 'flex';
    }
}

// 关闭添加店铺模态框
function closeAddShopModal() {
    document.getElementById('addShopModal').style.display = 'none';
    // 重置文件输入
    document.getElementById('addShopAvatar').value = '';
    document.getElementById('addShopImages').value = '';
}

// 提交添加店铺
function submitAddShop() {
    const formData = new FormData(document.getElementById('addShopForm'));

    // 表单验证
    if (!validateAddShopForm(formData)) {
        return;
    }

    showLoader();
    let avataList = [];
    const avatarNodes = document.querySelectorAll("#addShopImagesPreview .image-preview-item");
    for(var i = 0;i<avatarNodes.length;i++){
        if(avatarNodes[i].querySelector('img')){
            avataList.push(avatarNodes[i].querySelector('img').src)
        }
    }
    console.log(avataList)
    const submitFormData = new FormData();
    submitFormData.append("avatarUrl",document.querySelector("#addShopAvatarPreview").src)
    submitFormData.append("bannerUrls",JSON.stringify(avataList))
    submitFormData.append("name",document.querySelector("#addShopName").value)
    submitFormData.append("description",document.querySelector("#addShopDescription").value)
    submitFormData.append("ownerId",document.querySelector("#addShopOwnerId").value)
    submitFormData.append("status",document.querySelector("#addShopStatus").value)
    console.log(submitFormData)
    console.log(document.querySelector("#addShopDescription").value)
    $.ajax({
        url: '/shop/add',
        type: 'POST',
        data: submitFormData,
        processData: false,
        contentType: false,
        success: function(response) {
            if (response.code === 200) {
                showSuccessAlert('店铺添加成功');
                closeAddShopModal();
                renderTable();
            } else {
                showErrorAlert('添加失败: ' + response.message);
            }
        },
        error: function(xhr, status, error) {
            showErrorAlert('添加失败: ' + error);
        },
        complete: function() {
            hideLoader();
        }
    });
}

// 添加店铺表单验证
function validateAddShopForm(formData) {
    const name = formData.get('name');
    console.log(name)
    const ownerId = parseInt(formData.get('ownerId'));

    if (!name || name.trim().length < 2 || name.trim().length > 50) {
        showErrorAlert('店铺名称长度应为2-50个字符');
        return false;
    }

    if (isNaN(ownerId) || ownerId <= 0) {
        showErrorAlert('请输入有效的店主ID');
        return false;
    }

    return true;
}

// 图片文件验证
function validateImageFile(file) {
    if (!file.type.startsWith('image/')) {
        showErrorAlert('请选择图片文件（JPG、PNG等格式）');
        return false;
    }

    if (file.size > 2 * 1024 * 1024) {
        showErrorAlert('图片大小不能超过2MB');
        return false;
    }

    return true;
}
// 编辑店铺信息
function editShop(shopId) {
    showLoader();

    // 从服务器获取店铺详情
    $.ajax({
        url: '/shop/detail',
        type: 'POST',
        data: { id: shopId },
        success: function(response) {
            if (response.code === 200) {
                const shopData = response.data;
                populateEditShopForm(shopData);
                document.getElementById('editShopModal').style.display = 'flex';
                initEditShopUploads();
            } else {
                showErrorAlert('获取店铺详情失败: ' + response.message);
            }
        },
        error: function(xhr, status, error) {
            showErrorAlert('获取店铺详情失败: ' + error);
        },
        complete: function() {
            hideLoader();
        }
    });
}

// 填充编辑表单数据
function populateEditShopForm(shopData) {
    console.log(shopData)
    document.getElementById('editShopId').value = shopData.id || '';
    document.getElementById('editShopName').value = shopData.name || '';
    document.getElementById('editShopDescription').value = shopData.description || shopData.desc || '';
    document.getElementById('editShopOwnerId').value = shopData.ownerId || '';
    document.getElementById('editShopStatus').value = shopData.status || 0;

    // 设置头像预览
    const avatarPreview = document.getElementById('editShopAvatarPreview');
    const avatarPlaceholder = document.getElementById('editShopAvatarPlaceholder');
    if (shopData.avatarUrl || shopData.avatar_url) {
        avatarPreview.src = shopData.avatarUrl || shopData.avatar_url;
        avatarPreview.style.display = 'block';
        avatarPlaceholder.style.display = 'none';
    } else {
        avatarPreview.style.display = 'none';
        avatarPlaceholder.style.display = 'flex';
    }

    var imgs = JSON.parse(shopData.bannerUrls)
    console.log(imgs)
    // 设置店铺图片预览
    populateShopImagesPreview(imgs || []);
}

// 初始化编辑店铺上传功能
function initEditShopUploads() {
    initEditShopAvatarUpload();
    initEditShopImagesUpload();
}

// 初始化头像上传
function initEditShopAvatarUpload() {
    const avatarInput = document.getElementById('editShopAvatar');
    const preview = document.getElementById('editShopAvatarPreview');
    const placeholder = document.getElementById('editShopAvatarPlaceholder');
    const previewWrapper = document.querySelector('#editShopModal .avatar-preview-wrapper');

    // 点击预览区域选择文件
    previewWrapper.addEventListener('click', () => {
        avatarInput.click();
    });

    // 文件选择变化
    avatarInput.addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (file) {
            if (!validateImageFile(file)) {
                this.value = '';
                return;
            }

            const reader = new FileReader();
            reader.onload = function(event) {
                preview.src = event.target.result;
                preview.style.display = 'block';
                placeholder.style.display = 'none';
                const formData = new FormData();
                console.log("file是什么"+file)
                formData.append("file", file);  // "file" 必须和后端参数名一致
                $.ajax({
                    url: "/upload",  // 替换为你的Servlet URL
                    type: "POST",
                    data: formData,
                    processData: false,      // 禁止jQuery处理数据（文件上传必须）
                    contentType: false,      // 禁止设置Content-Type（浏览器自动生成multipart/form-data）
                    cache: false,            // 禁用缓存// 禁止设置Content-Type请求头（浏览器会自动设置）
                    success: function (response) {
                        imgSrc = response.data
                        console.log(imgSrc)
                        document.getElementById('editShopAvatarPreview').src=imgSrc
                    },error: function(xhr, status, error) {
                        console.error("上传失败:", error);
                        $("#result").html("上传失败: " + (xhr.responseText || error));
                    }
                });
            };
            reader.readAsDataURL(file);
        }
    });
}

// 初始化店铺图片上传
function initEditShopImagesUpload() {
    const imagesInput = document.getElementById('editShopImages');

    imagesInput.addEventListener('change', function(e) {
        const files = Array.from(e.target.files);
        if (files.length > 0) {
            handleShopImagesUpload(files);
        }
    });
}

// 触发店铺图片上传
function triggerShopImagesUpload() {
    document.getElementById('editShopImages').click();
}

// 处理店铺图片上传
function handleShopImagesUpload(files) {
    const previewContainer = document.getElementById('editShopImagesPreview');
    const existingImages = previewContainer.querySelectorAll('.image-preview-item:not(.add-image-btn)');
    // console.log(111)
    const imagesInput = document.getElementById('editShopImages');
    const formdata = new FormData()
    formdata.append("file",imagesInput.files[0])
    console.log(imagesInput.files[0])
    // formData.append("file", file);  // "file" 必须和后端参数名一致
    let img = null;
    $.ajax({
        url: "/upload",  // 替换为你的Servlet URL
        type: "POST",
        data: formdata,
        processData: false,      // 禁止jQuery处理数据（文件上传必须）
        contentType: false,      // 禁止设置Content-Type（浏览器自动生成multipart/form-data）
        cache: false, // 禁用缓存// 禁止设置Content-Type请求头（浏览器会自动设置）
        async:false,
        success: function (response) {
            img = response.data
            console.log(img)
        },error: function(xhr, status, error) {
            console.error("上传失败:", error);
            $("#result").html("上传失败: " + (xhr.responseText || error));
        }
    });
    // 检查图片数量限制
    if (existingImages.length + files.length > 6) {
        showErrorAlert('最多只能上传6张图片');
        return;
    }

    files.forEach((file, index) => {
        if (!validateImageFile(file)) return;

        const reader = new FileReader();
        reader.onload = function(event) {
            const imageItem = createImagePreviewItem(img, img);
            // 插入到添加按钮之前
            const addBtn = previewContainer.querySelector('.add-image-btn');
            previewContainer.insertBefore(imageItem, addBtn);
        };
        reader.readAsDataURL(file);
    });

    // 如果达到最大数量，隐藏添加按钮
    updateAddImageButtonVisibility();
}

// 创建图片预览项
function createImagePreviewItem(src, filename) {
    const item = document.createElement('div');
    item.className = 'image-preview-item';
    item.innerHTML = `
        <img src="${src}" alt="${filename}">
        <button type="button" class="image-remove-btn" onclick="removeShopImage(this)">
            <i class="bi bi-x"></i>
        </button>
    `;
    return item;
}

// 移除店铺图片
function removeShopImage(button) {
    const item = button.closest('.image-preview-item');
    item.remove();
    updateAddImageButtonVisibility();
}

// 更新添加按钮可见性
function updateAddImageButtonVisibility() {
    const previewContainer = document.getElementById('editShopImagesPreview');
    const existingImages = previewContainer.querySelectorAll('.image-preview-item:not(.add-image-btn)');
    const addBtn = previewContainer.querySelector('.add-image-btn');

    if (existingImages.length >= 6) {
        addBtn.style.display = 'none';
    } else {
        addBtn.style.display = 'flex';
    }
}

// 填充店铺图片预览
function populateShopImagesPreview(images) {
    const previewContainer = document.getElementById('editShopImagesPreview');
    // 清空现有图片（保留添加按钮）
    const existingImages = previewContainer.querySelectorAll('.image-preview-item:not(.add-image-btn)');
    existingImages.forEach(img => img.remove());

    // 添加新图片
    images.forEach((image, index) => {
        const imageItem = createImagePreviewItem(image, `店铺图片${index + 1}`);
        const addBtn = previewContainer.querySelector('.add-image-btn');
        previewContainer.insertBefore(imageItem, addBtn);
    });

    updateAddImageButtonVisibility();
}

// 关闭编辑店铺模态框
function closeEditShopModal() {
    document.getElementById('editShopModal').style.display = 'none';
    // 重置文件输入
    document.getElementById('editShopAvatar').value = '';
    document.getElementById('editShopImages').value = '';
}

// 保存店铺更改
function saveShopChanges() {
    const formData = new FormData(document.getElementById('editShopForm'));

    // 添加店铺图片文件
    const imagesInput = document.getElementById('editShopImages');
    const imageFiles = imagesInput.files;
    for (let i = 0; i < imageFiles.length; i++) {
        formData.append('images', imageFiles[i]);
    }

    // 表单验证
    if (!validateShopForm(formData)) {
        return;
    }

    showLoader();
    let avataList = [];
    const avatarNodes = document.querySelectorAll("#editShopImagesPreview .image-preview-item");
    for(var i = 0;i<avatarNodes.length;i++){
        if(avatarNodes[i].querySelector('img')){
            avataList.push(avatarNodes[i].querySelector('img').src)
        }
    }
    console.log(avataList)
    const submitFormData = new FormData();
    submitFormData.append("id",document.querySelector("#editShopId").value)
    submitFormData.append("avatarUrl",document.querySelector("#editShopAvatarPreview").src)
    submitFormData.append("bannerUrls",JSON.stringify(avataList))
    submitFormData.append("name",document.querySelector("#editShopName").value)
    submitFormData.append("description",document.querySelector("#editShopDescription").value)
    submitFormData.append("ownerId",document.querySelector("#editShopOwnerId").value)
    submitFormData.append("status",document.querySelector("#addShopStatus").value)
    console.log(submitFormData)
    console.log(document.querySelector("#editShopStatus").value)

    $.ajax({
        url: '/shop/update',
        type: 'POST',
        data: submitFormData,
        processData: false,
        contentType: false,
        success: function(response) {
            if (response.code === 200) {
                showSuccessAlert('店铺信息更新成功');
                closeEditShopModal();
                renderTable();
            } else {
                showErrorAlert('更新失败: ' + response.message);
            }
        },
        error: function(xhr, status, error) {
            showErrorAlert('更新失败: ' + error);
        },
        complete: function() {
            hideLoader();
        }
    });
}

// 店铺表单验证
function validateShopForm(formData) {
    const name = formData.get('name');
    const ownerId = parseInt(formData.get('ownerId'));

    if (!name || name.trim().length < 2 || name.trim().length > 50) {
        showErrorAlert('店铺名称长度应为2-50个字符');
        return false;
    }

    if (isNaN(ownerId) || ownerId <= 0) {
        showErrorAlert('请输入有效的店主ID');
        return false;
    }

    return true;
}

// 图片文件验证
function validateImageFile(file) {
    if (!file.type.startsWith('image/')) {
        showErrorAlert('请选择图片文件（JPG、PNG等格式）');
        return false;
    }

    if (file.size > 2 * 1024 * 1024) {
        showErrorAlert('图片大小不能超过2MB');
        return false;
    }

    return true;
}
// 轮播图状态
let currentCarouselIndex = 0;
let shopImages = [];

// 查看店铺详情
function viewShop(shopId) {
    showLoader();

    // 从服务器获取店铺详情
    $.ajax({
        url: '/shop/detail',
        type: 'POST',
        data: { id: shopId },
        success: function(response) {
            if (response.code === 200) {
                const shopData = response.data;
                populateViewShopModal(shopData);
                document.getElementById('viewShopModal').style.display = 'flex';
            } else {
                showErrorAlert('获取店铺详情失败: ' + response.message);
            }
        },
        error: function(xhr, status, error) {
            showErrorAlert('获取店铺详情失败: ' + error);
        },
        complete: function() {
            hideLoader();
        }
    });
}

// 填充查看模态框数据
function populateViewShopModal(shopData) {
    console.log(shopData);
    // 基本信息
    document.getElementById('viewShopId').textContent = shopData.id || '-';
    document.getElementById('viewShopName').textContent = shopData.name || '-';
    document.getElementById('viewShopOwnerId').textContent = shopData.username;
    document.getElementById('viewShopRating').textContent = shopData.rating || 0;
    document.getElementById('viewRatingCount').textContent = shopData.ratingCount || shopData.rating_count || 0;
    document.getElementById('viewShopCreateTime').textContent = shopData.createTime || '-';
    document.getElementById('viewShopDescription').textContent = shopData.description || shopData.desc || '-';
    document.getElementById('viewShopFavorites').textContent = shopData.favoriteCount || 0;
    document.getElementById('viewShopCheckins').textContent = shopData.checkinCount || 0;
    document.getElementById('viewShopReviews').textContent = shopData.reviewCount || 0;

    // 设置头像
    const avatarImg = document.getElementById('viewShopAvatar');
    if (shopData.avatarUrl || shopData.avatar_url) {
        avatarImg.src = shopData.avatarUrl || shopData.avatar_url;
        avatarImg.style.display = 'block';
    } else {
        avatarImg.style.display = 'none';
    }

    // 设置轮播图
    setupShopCarousel(JSON.parse(shopData.bannerUrls) || []);
}

// 设置店铺轮播图
function setupShopCarousel(images) {
    shopImages = images;
    currentCarouselIndex = 0;

    const carousel = document.getElementById('viewShopCarousel');
    const indicators = document.getElementById('viewShopIndicators');
    const noImagesMessage = document.getElementById('noImagesMessage');

    // 清空现有内容
    carousel.innerHTML = '';
    indicators.innerHTML = '';

    if (images.length === 0) {
        // 显示无图片提示
        noImagesMessage.style.display = 'block';
        document.querySelector('.carousel-container').style.display = 'none';
        document.getElementById('currentSlide').textContent = '0';
        document.getElementById('totalSlides').textContent = '0';
        return;
    }

    // 隐藏无图片提示，显示轮播图
    noImagesMessage.style.display = 'none';
    document.querySelector('.carousel-container').style.display = 'block';
    console.log(images[0])
    // 创建轮播图幻灯片
    images.forEach((image, index) => {
        const slide = document.createElement('div');
        slide.className = 'carousel-slide';
        slide.innerHTML = `<img src="${image.url || image}" alt="店铺图片 ${index + 1}" onerror="this.src='/images/default-shop-image.jpg'">`;
        carousel.appendChild(slide);

        // 创建指示器
        const indicator = document.createElement('button');
        indicator.className = `carousel-indicator ${index === 0 ? 'active' : ''}`;
        indicator.onclick = () => goToSlide(index);
        indicators.appendChild(indicator);
    });

    // 更新计数器
    document.getElementById('currentSlide').textContent = '1';
    document.getElementById('totalSlides').textContent = images.length.toString();

    // 更新轮播图位置
    updateCarouselPosition();
}

// 更新轮播图位置
function updateCarouselPosition() {
    const carousel = document.getElementById('viewShopCarousel');
    const indicators = document.querySelectorAll('.carousel-indicator');

    // 移动轮播图
    carousel.style.transform = `translateX(-${currentCarouselIndex * 100}%)`;

    // 更新指示器状态
    indicators.forEach((indicator, index) => {
        indicator.classList.toggle('active', index === currentCarouselIndex);
    });

    // 更新计数器
    document.getElementById('currentSlide').textContent = (currentCarouselIndex + 1).toString();
}

// 下一张幻灯片
function nextSlide() {
    if (shopImages.length === 0) return;

    currentCarouselIndex = (currentCarouselIndex + 1) % shopImages.length;
    updateCarouselPosition();
}

// 上一张幻灯片
function prevSlide() {
    if (shopImages.length === 0) return;

    currentCarouselIndex = (currentCarouselIndex - 1 + shopImages.length) % shopImages.length;
    updateCarouselPosition();
}

// 跳转到指定幻灯片
function goToSlide(index) {
    if (index >= 0 && index < shopImages.length) {
        currentCarouselIndex = index;
        updateCarouselPosition();
    }
}

// 关闭查看店铺模态框
function closeViewShopModal() {
    document.getElementById('viewShopModal').style.display = 'none';
    // 重置轮播图状态
    currentCarouselIndex = 0;
    shopImages = [];
}

// 自动轮播（可选）
function startAutoCarousel() {
    if (shopImages.length > 1) {
        setInterval(() => {
            nextSlide();
        }, 5000); // 每5秒自动切换
    }
}

// 在模态框打开后启动自动轮播
document.addEventListener('DOMContentLoaded', function() {
    const viewModal = document.getElementById('viewShopModal');
    if (viewModal) {
        viewModal.addEventListener('click', function(e) {
            if (e.target === this) {
                closeViewShopModal();
            }
        });
    }
});
function showErrorAlert(message) {
    const errorAlert = document.getElementById('error-alert');
    const errorMessage = document.getElementById('error-message');

    errorMessage.textContent = message;
    errorAlert.style.display = 'flex';

    // 3秒后自动隐藏
    setTimeout(() => {
        errorAlert.style.display = 'none';
    }, 3000);
}
function showSuccessAlert(message) {
    const successAlert = document.getElementById('success-alert');
    const successMessage = document.getElementById('success-message');

    successMessage.textContent = message;
    successAlert.style.display = 'flex';

    // 3秒后自动隐藏
    setTimeout(() => {
        successAlert.style.display = 'none';
    }, 3000);
}